<template>
  <el-dialog v-model="signDialog" :append-to-body="true" :close-on-click-modal="false" style="background-color: #ffffff; box-sizing: border-box"  @close="onClose">
    <!-- 主体内容 -->
    <div class="activity-detail-container flex justify-content-space-between">
      <!-- 中板块  -->
      <div style="margin-top: 20px;width: 100%">
        <div style="background-color: #ffffff;margin-right: 10px">
          <div style="width: 100%;border-bottom: 1px solid #dedcdc;padding:0 0 10px 0;margin: 0 0 20px 0;font-size: 18px;color: #3d3838;font-weight: bolder">签到管理</div>
          <div class="flex justify-content-space-between">
            <div style="margin-right: 10px" class="flex-auto">
              <div class="sign_manager">签到管理</div>
              <div class="flex " style="margin-top: 20px">
                <div class="flex-auto" style="border: 1px solid #eeeef3;border-radius: 10px;margin-right: 5px;padding: 10px;">
                  <div class="img-box flex justify-content-center align-center" style="background-color: #F9FAFB;padding: 30px 0;border-radius: 10px">
                    <img src="../../../../assets/smart/二维码签到.png" style="height: 50px;display: block" alt="">
                  </div>
                  <div style="text-align: center;color: #3B3B3B;font-size: 16px;font-weight: bolder;margin-top: 10px">二维码签到</div>
                  <div style="text-align: center;color: #999999;font-size: 12px">扫码快速签到</div>
                </div>
                <div class="flex-auto" style="border: 1px solid #eeeef3;border-radius: 10px;margin-left: 5px;padding: 10px;" @click="openSignDialog">
                  <div class="img-box  flex justify-content-center align-center" style="background-color: #F9FAFB;padding: 30px 0;border-radius: 10px">
                    <img src="../../../../assets/smart/手动签到.png" style="height: 50px;display: block" alt="">
                  </div>
                  <div style="text-align: center;color: #3B3B3B;font-size: 16px;font-weight: bolder;margin-top: 10px"  >手动签到</div>
                  <div style="text-align: center;color: #999999;font-size: 12px">线下登记签到</div>
                </div>
              </div>
              <!-- 搜索党员姓名 -->
              <div class="sign-person-container" style="border: 1px solid #eeeef3;margin-top: 20px;border-radius: 10px;padding: 20px">
                <div class="flex align-center justify-content-space-between">
                  <el-select filterable v-model="signPerson" placeholder="搜索党员姓名" style="width: 100%" clearable>
                     <el-option v-for="(item,index) in activityUserInfoList" :label="item.cpcInfo.pbUserName" :value="item.cpcInfo.id" :key="index" />
                  </el-select>
                  <el-button style="margin-left: 20px"  type="primary" icon="Plus" @click="addSign">添加签到</el-button>
                </div>
                <div class="flex justify-content-space-between" style="margin-top: 20px">
                  <div style="color: black;font-weight: bolder">已签到人员</div>
                  <div>共<span style="color: red;padding: 0 5px">{{signAndLeaveList.signList.length}}</span>人</div>
                </div>
                <!---------------------------------------------->
                <div class="sign-in-list" style="height: 285px;">
                  <div v-for="(item, index) in signAndLeaveList.signList" :key="index" class="sign-item" style="width: 48%;">
                    <div class="avatar">{{ item.cpcInfo.pbUserName.charAt(0) }}</div>
                    <div style="flex: 1;">
                      <div style="font-weight: bold; color: #333;">{{ item.cpcInfo.pbUserName }}</div>
                      <div style="color: #999; font-size: 12px;">今天 {{ item.manageTime }}</div>
                    </div>
                    <div class="status">{{item.manageState == 1?'已签到':'已请假'}}</div>
                  </div>
                </div>
                <!---------------------------------------------->
              </div>
            </div>
            <div style="margin-left: 10px" class="flex-auto">
              <div class="sign_manager">请假管理</div>
              <!-- 搜索党员姓名 -->
              <div class="sign-person-container " style="border: 1px solid #eeeef3;margin-top: 20px;border-radius: 10px;padding: 20px">
                <div class="flex align-center justify-content-space-between">
                  <el-select filterable v-model="leavePerson" placeholder="搜索党员姓名"  class="responsive-input" style="width: 100%"  clearable>
                    <el-option v-for="(item,index) in activityUserInfoList" :label="item.cpcInfo.pbUserName" :value="item.cpcInfo.id" :key="index" />
                  </el-select>
                  <el-button style="margin-left: 20px"  type="primary" icon="Plus"  @click="addLeave">添加请假</el-button>
                </div>
                <div class="flex justify-content-space-between" style="margin-top: 20px">
                  <div style="color: black;font-weight: bolder">请假人员</div>
                  <div>共<span style="color: red;padding: 0 5px">{{signAndLeaveList.leaveList.length}}</span>人</div>
                </div>
                <div class="sign-in-list"  style="height: 458px;">
                  <div v-for="(item, index) in signAndLeaveList.leaveList" :key="index" class="sign-item" style="width: 100%;">
                    <!-- 头像 -->
                    <div class="avatar">{{ item.cpcInfo.pbUserName.charAt(0) }}</div>
                    <!-- 姓名与时间 -->
                    <div style="flex: 1;">
                      <div style="font-weight: bold; color: #333;">{{ item.cpcInfo.pbUserName }}</div>
                      <div style="color: #999; font-size: 12px;">{{item.manageReason}}</div>
                    </div>
                    <div class="flex align-center">
                      <div v-if="item.status==0">
                        <el-button size="small" type="success">同意</el-button>
                        <el-button size="small" type="primary">拒绝</el-button>
                      </div>
                      <!-- 状态标签 -->
                      <div class="status" v-if="item.status==1">已批准</div>
                      <div class="status" v-if="item.status==2">未批准</div>
                    </div>
                  </div>
                </div>
                <!---------------------------------------------->
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 签到弹窗组件 -->
      <SignPage ref="signPageRef" />
    </div>
  </el-dialog>
</template>
<script setup>
import {ref, computed} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import SignDialog from './SignDialog.vue';
import {Calendar, LocationFilled, Document, Download, Edit, Delete, Search} from '@element-plus/icons-vue';
import {
  getActivityDetails,
  getActivityUserList,
  getUserNameInfo,
  upActivityManagement
} from "@/api/life/relationship.js";
import SignPage from './SignPage.vue';
// 接收父组件传递的 visible 开关
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  activity: {
    type: Object,
    required: false
  },
});
// 发送事件给父组件
const emit = defineEmits(['update:modelValue', 'save']);
const signPageRef = ref(null);
const signPerson = ref('');
const leavePerson = ref('');
const activityId = ref('');
const signAndLeaveList = ref({
  signList:[],
  leaveList:[]
});
const activityUserInfoList = ref([]);
const partyMemberList = ref([]);  // 全部党员



const openSignDialog = () => {
  if (signPageRef.value) {
    signPageRef.value.show();
  }
  nextTick(() => {
    if (signPageRef.value) {
       signPageRef.value.loadSignList(activityId.value);
    }
  });





};
defineExpose({
  loadSignList
});
// 弹窗可见性
const signDialog = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
    // 当对话框打开时，确保数据是干净的
    if (value) {
      signPerson.value = '';
      leavePerson.value = '';
      activityId.value = '';
      signAndLeaveList.value = {
        signList: [],
        leaveList: []
      };
      activityUserInfoList.value = [];
      partyMemberList.value = [];
    }
  }
});


// 定义 onClose 方法
const onClose = () => {
  signPerson.value = '';
  leavePerson.value = '';
  activityId.value = '';
  signAndLeaveList.value = {
    signList: [],
    leaveList: []
  };
  activityUserInfoList.value = [];
  partyMemberList.value = [];
};

// 获取参会人员
const getUserNameList = async () => {
  let result = await getUserNameInfo();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
    partyMemberList.value = data;
  }
}

// 获取签到信息集合
async function loadSignList(id) {
  try {
    const response = await getActivityUserList({ activityID: id });
    if (response.status == 200 && response.data.code == 200) {
      let data = response.data.data;
      signAndLeaveList.value = {
        signList: data.registerUserInfoList,
        leaveList: data.sickUserInfoList
      };
      await loadActivityDetails(id);
    }
  } catch (error) {
    ElMessage.error('加载活动信息时发生错误');
  }
}

// 获取活动详情
async function loadActivityDetails(id) {
    activityId.value = id;
    const response = await getActivityDetails({ guid: activityId.value });
    if (response.status == 200 && response.data.code == 200) {
      activityUserInfoList.value = response.data.data.activityUserInfoList;
      console.log(activityUserInfoList.value)
    }
}

const addSign = async () => {
  if (activityUserInfoList.length == 0) {
    ElMessage.error('当前设定参加该活动的人员,无法添加签到！');
  } else {
     if (signPerson.value == ''){
        ElMessage.error('请选择党员姓名,否则无法添加签到！');
       return false;
     }

    const signList = {
      activityId: activityId.value,
      registerUserInfoList: [{
        activityUserInfoId: signPerson.value,
        manageTime: getCurrentTime()
      }],
      sickUserInfoList: []
    };
    const response = await upActivityManagement(signList);
    if (response.status == 200 && response.data.code == 200) {
      let data = response.data.data;
      await loadSignList(activityId.value)
    }
  }
}
const addLeave =async () => {
  if (activityUserInfoList.length == 0) {
    ElMessage.error('当前设定参加该活动的人员,无法添加请假！');
  } else {
    if (leavePerson.value == '') {
      ElMessage.error('请选择党员姓名,否则无法添加请假！');
      return false;
    }
    ElMessageBox.prompt('请输入请假理由！',  {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputErrorMessage: 'Invalid',
    }).then(async ({value}) => {
      const leaveList = {
        activityId: activityId.value,
        registerUserInfoList: [],
        sickUserInfoList: [{
          activityUserInfoId: leavePerson.value,
          manageReason: value
        }]
      };
      const response = await upActivityManagement(leaveList);
      if (response.status == 200 && response.data.code == 200) {
        let data = response.data.data;
        await loadSignList(activityId.value)
      }
    }).catch(() => {

    })

  }
}


// 获取当前时间并格式化为 YYYY-MM-DD HH:MM:SS
function getCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}




getUserNameList();




</script>
<style lang="scss" scoped>
  .sign-in-list {
    background-color: #F9FAFB;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
   overflow-y: auto;
    margin-top: 10px;
    gap: 8px;
    align-content: flex-start;
    .sign-item{
      display: flex;
      align-items: center;
      padding: 10px;
      border-radius: 8px;
      background: white;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      font-size: 14px;
      height: fit-content;
      .avatar{
        width: 32px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background: #E5E7EB;
        border-radius: 50%;
        margin-right: 10px;
        font-size: 16px;
        color: #333333;
      }
      .status{
        color: #22C45E;
        font-size: 12px;
        padding: 2px 6px;

        border-radius: 4px;
      }
    }
  }
  .status-container{
    background-color: #FFFFFF;
    .status-item{
      height: fit-content;
      padding: 20px 0;
      background-color: #ffffff;
      border-radius: 8px;
       border: 1px solid #E5E7EB;
      .status-desc{
        margin-top: 10px;
        color: #333333;
        font-weight: bolder;
        text-align: center;
      }
    }

  }




</style>
